import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

// 创建 axios 实例
const axiosInstance: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加 token
    const token = localStorage.getItem('token');
    if (token && config.headers) {
      config.headers.Authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 统一处理响应
    const { data } = response;
    if (data.code === 200) {
      if (data.msg && data.msg !== '成功') {
        ElMessage.success(data.msg);
      }
      return data;
    } else if (data.code === 304) {
      localStorage.removeItem('token');
      router.push('/login');
      ElMessage.error(data.msg || '登录已过期，请重新登录');
    } else if (data.code === 303) {
      ElMessage.error(data.msg);
      router.push('/login');
    } else {
      ElMessage.error(data.msg || '请求失败');
      // localStorage.removeItem('token');
      return data;
    }
  },
  (error) => {
    // 处理网络错误
    ElMessage.error('网络错误，请稍后再试');
    console.log(error);
    return Promise.reject(error);
  }
);

export default axiosInstance;